package com.xatu.yl.storeshopping.activity.Fragment;


import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.namespace.R;
import com.xatu.yl.storeshopping.vo.ShopInfo;
import com.xatu.yl.storeshopping.vo.ShoppingInfo;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class AwaitDeliveryFragment extends Fragment implements View.OnClickListener {
    private View root;
    private EditText search;

    private ListView pro_list;
    private TextView hint;
    //店铺信息
    private List<ShopInfo> shopInfoList = new ArrayList<>();
    //订单中的商品信息
    private List<ShoppingInfo> shoppingInfoList = new ArrayList<>();
    private Spinner spinner;
    //定义一个用来存放CommitData类型的集合
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //如果不存在，则创建
        if(root==null){
            root=inflater.inflate(R.layout.fragment_await_delivery, container, false);
        }

        //定义下拉列表
        spinner = root.findViewById(R.id.searchType);

        // 从资源文件中加载字符串数组作为数据源
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.search_type, android.R.layout.simple_spinner_item);

        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 将适配器设置到Spinner上
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(spinnerSelect);
        spinner.setSelection(0);


        //上导航栏，点击切换首页的展示内容
        search=root.findViewById(R.id.search);
        search.setOnClickListener(this);
        //搜索框的提示文字
        hint = root.findViewById(R.id.hint);
        hint.setText("搜索店铺");

        //设置初始为未选中状态
        search.setFocusable(false);
        search.setFocusableInTouchMode(false);
        pro_list=root.findViewById(R.id.pro_list);

        //设置事件监听
        search.setOnClickListener(this);

        //店铺信息
        for(int i=0;i<10;i++){
            shopInfoList.add(new ShopInfo("","多赞","123","2￥/个","大家案发地撒欧弟的风"));
        }

        //订单中商品的信息
        for(int i=0;i<4;i++){
            shoppingInfoList.add(new ShoppingInfo("","海底捞","12","10"));
        }
        //绑定适配器,设置适配器

        pro_list.setAdapter(new OrderListAdapter());
        pro_list.setOnItemClickListener(orderInfoListener);
        return root;
    }

    //点击订单
    AdapterView.OnItemClickListener orderInfoListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    };

    //下拉列表点击事件

    AdapterView.OnItemSelectedListener spinnerSelect = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // 在这里处理选中某个 Item 后的逻辑
            if(position==0){
                hint.setText("搜索店铺");
            }
            if(position==1){
                hint.setText("搜索订单");
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // 当没有选中任何 Item 时的处理逻辑
        }
    };


    //为点击设计事件监听
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.search){
            //不管之前是否为选中状态
            //这里都设置选中
            search.setFocusable(true);
            search.setFocusableInTouchMode(true);
            //同时点击搜索框的时候，将文字取消
            hint.setText("");
        }
    }

    //适配器，加载整个pro_list中的内容
    public class OrderListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return shopInfoList.size();
        }

        @Override
        public Object getItem(int i) {
            return shopInfoList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View item = View.inflate(getActivity().getApplicationContext(), R.layout.await_delivery_pro_list_items, null);
            /**
             * shop_icon：商品图标
             * shop_name：商品名称
             * shop_sale_month：商品月销量
             * shop_price：商品价格
             * shop_description：商品描述
             */
            ImageView shop_icon = item.findViewById(R.id.shop_icon);
            TextView shop_name = item.findViewById(R.id.shop_name);
            TextView shop_sale_month = item.findViewById(R.id.shop_sale_month);
            TextView shop_price = item.findViewById(R.id.shop_price);
            TextView shop_description = item.findViewById(R.id.shop_description);
            //订单信息列表
            RecyclerView shopping_list = item.findViewById(R.id.shopping_list);
            Button cancel_order = item.findViewById(R.id.cancel_order);
            TextView total_money = item.findViewById(R.id.total_money);

            //绑定订单中商品的适配器

            LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
            shopping_list.setLayoutManager(linearLayoutManager);
            shopping_list.setAdapter(new ShoppingAdapter(getActivity().getApplicationContext()));


            //从集合中获取数据
//            ShopInfo shopInfo = shopInfoList.get(i);
//
//            // 图片
//            if(shopInfo.getShop_icon().equals("")){
//                shop_icon.setImageResource(R.drawable.error_photo);
//            }else{
//                new LoadImageTask(shop_icon).execute(shopInfo.getShop_icon());
//            }
//
//            shop_name.setText(shopInfo.getShop_name());
//            shop_sale_month.setText(shopInfo.getShop_sale_month());
//            shop_price.setText(shopInfo.getShop_price());
//            shop_description.setText(shopInfo.getShop_description());

            return item;
        }
    }



    /**
     * 1.网络请求和图片加载：
     * 在 AsyncTask 的 doInBackground 方法中，我们执行网络请求，获取指定URL的图片数据流，并通过 BitmapFactory.decodeStream 方法将其解码为 Bitmap 对象。
     * 2.异步加载：
     * 使用 AsyncTask 来异步执行图片加载操作，确保在主线程之外进行网络请求，以避免阻塞主线程，从而保持应用的响应性。
     * 3.显示图片：
     * 在 onPostExecute 方法中，我们检查解码后的 Bitmap 是否为空，如果不为空，则将其设置到预先定义的 ImageView 中显示出来。
     * 4.为了避免 NetworkOnMainThreadException 异常，不能在主线程中执行网络请求。因此，使用 AsyncTask 或者其他异步加载方式是推荐的做法。
     */

    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView imageView;
        public LoadImageTask(ImageView imageView){
            this.imageView = imageView;
        }
        @Override
        protected Bitmap doInBackground(String... strings) {
            String imageUrl = strings[0];
            Bitmap bitmap = null;
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }


    //为一个订单中的商品信息设置适配器
    public class ShoppingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private Context context;

        public ShoppingAdapter(Context context) {
            this.context = context;
        }

        //设置每条数据的展示布局文件
        @NonNull
        @Override
        public ShoppingAdapter.MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            MyHolder myHolder=new MyHolder(LayoutInflater.from(context).inflate(R.layout.await_delivery_shopinfo_list_items,viewGroup,false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ImageView shopping_icon = holder.itemView.findViewById(R.id.shopping_icon);
            TextView shopping_name = holder.itemView.findViewById(R.id.shopping_name);
            TextView shopping_number = holder.itemView.findViewById(R.id.shopping_number);
            TextView shopping_price = holder.itemView.findViewById(R.id.shopping_price);

            //获取数据对象
            ShoppingInfo shoppingInfo = shoppingInfoList.get(position);
            //绑定数据
//            shopping_icon.setImageBitmap();
            shopping_name.setText(shoppingInfo.getShopping_name());
            shopping_number.setText(shoppingInfo.getShopping_number());
            shopping_price.setText(shoppingInfo.getShopping_price());
        }

        @Override
        public int getItemCount() {
            return shoppingInfoList.size();
        }

        public class MyHolder extends RecyclerView.ViewHolder {
            private ImageView shopping_icon;
            private TextView shopping_name;
            private TextView shopping_number;
            private TextView shopping_price;
            public MyHolder(@NonNull View itemView) {
                super(itemView);
                shopping_icon = itemView.findViewById(R.id.shopping_icon);
                shopping_name = itemView.findViewById(R.id.shopping_name);
                shopping_number = itemView.findViewById(R.id.shopping_number);
                shopping_price = itemView.findViewById(R.id.shopping_price);
            }
        }
    }
}


